const app = getApp();

Page({
  data: {
    loading: true,
    address: null,
    orderItems: [],
    remark: '',
    totalPrice: 0,
    totalQuantity: 0
  },

  onLoad(options) {
    const orderItems = wx.getStorageSync('orderItems') || [];
    if (orderItems.length === 0) {
      wx.showToast({
        title: '订单信息不完整',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    // 计算总价和总数量
    const totalPrice = orderItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
    const totalQuantity = orderItems.reduce((sum, item) => sum + item.quantity, 0);

    this.setData({
      orderItems,
      totalPrice,
      totalQuantity
    });
  },

  onShow() {
    this.loadDefaultAddress();
  },

  async loadDefaultAddress() {
    try {
      const res = await app.request({
        url: '/address/default/',
        method: 'GET'
      });

      if (res.code === 200) {
        this.setData({
          address: res.data,
          loading: false
        });
      } else {
        this.setData({
          loading: false
        });
      }
    } catch (error) {
      console.error('获取默认地址失败', error);
      this.setData({
        loading: false
      });
    }
  },

  goToAddressList() {
    wx.navigateTo({
      url: '/pages/address/list/list?from=order'
    });
  },

  handleRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  async handleSubmit() {
    if (!this.data.address) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      });
      return;
    }

    const orderData = {
      address_id: this.data.address.id,
      items: this.data.orderItems.map(item => ({
        sku_id: item.sku_id,
        quantity: item.quantity
      })),
      remark: this.data.remark
    };

    try {
      const res = await app.request({
        url: '/order/orders/create_order/',
        method: 'POST',
        data: orderData
      });

      if (res.code === 200) {
        // 清除订单缓存
        wx.removeStorageSync('orderItems');
        
        // 更新购物车数量
        app.updateCartCount();

        // 跳转到支付页面
        wx.redirectTo({
          url: `/pages/order/pay/pay?order_id=${res.data.id}`
        });
      } else {
        wx.showToast({
          title: res.message || '创建订单失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('创建订单失败：', error);
      wx.showToast({
        title: '创建订单失败',
        icon: 'none'
      });
    }
  }
}); 